<template>
  <el-upload
    class="avatar-uploader"
    action="/api/file/img/upload"
    :show-file-list="false"
    :http-request="onHttpRequest"
    :on-success="handleAvatarSuccess"
  >
    <img alt="" v-if="imageUrl" :src="imageUrl" class="avatar" width="200" height="200" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>

</template>

<script setup lang="ts">

import { Plus } from "@element-plus/icons-vue";
import { createAxios } from "~/api/util/request-wrapper";
import { JsonResult } from "~/api/types";
import { fileMd5 } from "~/api/util/FileMd5";
import { onMounted, ref, watch } from "vue";

interface Props {
  modelValue?: string;
}

const props = withDefaults(defineProps<Props>(), {});
const http = createAxios();
const imageUrl = ref("");
let emits = defineEmits("update:modelValue");

async function onHttpRequest({ file }: any) {
  const md5: {
    md5: string,
    sliceMd5s: {
      currentChunk: number,
      md5: string,
    }[]
  } = await fileMd5(file);
  const formData = new FormData();
  formData.set("file", file);
  formData.set("md5", md5.md5);
  formData.set("isPublic", String(true));
  formData.set("fileName", file.name);
  return await http.post("/file/img/upload", formData, { headers: { "Authorization": "Bearer " + localStorage.getItem("token") } });
}

async function handleAvatarSuccess(response: JsonResult<any>) {
  emits("update:modelValue", response.data);
}

watch(() => props.modelValue, async (value: any) => {
  if (value) {
    const res: any = await http.get(value, { responseType: "blob", headers: { "Authorization": "Bearer " + localStorage.getItem("token") } });
    imageUrl.value = URL.createObjectURL(res);
  }
}, { immediate: true });
</script>

<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader {
  &:hover {
    border-color: var(--el-color-primary);
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  text-align: center;
}
</style>
